package com.example.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.reggie.common.Result;
import com.example.reggie.domain.*;
import com.example.reggie.dto.OrdersDto;
import com.example.reggie.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.yaml.snakeyaml.serializer.NumberAnchorGenerator;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@RequestMapping("/order")
@Slf4j
@RestController
public class OrderController {

    @Autowired
    OrdersService ordersService;

    @Autowired
    ShoppingCartService shoppingCartService;

    @Autowired
    OrderDetailService orderDetailService;

    @Autowired
    AddressBookService addressBookService;

    @Autowired
    UserService userService;

    // 用户端的订单分页查询
    @GetMapping("/userPage")
    Result<Page> orderUserPageList(Integer page, Integer pageSize, HttpServletRequest request){
        Page<Orders> ordersPage = new Page<>(page,pageSize);
        Page<OrdersDto> ordersDtoPage = new Page<>();
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Orders::getUserId,request.getSession().getAttribute("user"));
        ordersService.page(ordersPage,queryWrapper);
        List<Orders> orders = ordersPage.getRecords();
        List<OrdersDto> ordersDtos = new ArrayList<>();
        for (int i = 0; i < orders.size(); i++) {
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(orders.get(i),ordersDto);
            LambdaQueryWrapper<OrderDetail> orderDetailLambdaQueryWrapper = new LambdaQueryWrapper<>();
            orderDetailLambdaQueryWrapper.eq(OrderDetail::getOrderId,orders.get(i).getId());
            List<OrderDetail> orderDetails = orderDetailService.list(orderDetailLambdaQueryWrapper);
            ordersDto.setOrderDetails(orderDetails);
            ordersDtos.add(ordersDto);
        }
        BeanUtils.copyProperties(ordersPage,ordersDtoPage,"records");
        ordersDtoPage.setRecords(ordersDtos);
        return Result.success(ordersDtoPage);

    }

    // 管理端的订单分页查询
    @GetMapping("/page")
    Result<Page> orderPageList(Integer page, Integer pageSize, String number, LocalDateTime beginTime,LocalDateTime endTime){
        Page<Orders> ordersPage = new Page<>(page,pageSize);
        Page<OrdersDto> ordersDtoPage = new Page<>();
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(number!=null,Orders::getNumber,number);
        queryWrapper.between(beginTime!=null&&endTime!=null,Orders::getOrderTime,beginTime,endTime);
        ordersService.page(ordersPage,queryWrapper);
        List<Orders> orders = ordersPage.getRecords();
        List<OrdersDto> ordersDtos = new ArrayList<>();
        for (int i = 0; i < orders.size(); i++) {
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(orders.get(i),ordersDto);
            LambdaQueryWrapper<OrderDetail> orderDetailLambdaQueryWrapper = new LambdaQueryWrapper<>();
            orderDetailLambdaQueryWrapper.eq(OrderDetail::getOrderId,orders.get(i).getId());
            List<OrderDetail> orderDetails = orderDetailService.list(orderDetailLambdaQueryWrapper);
            ordersDto.setOrderDetails(orderDetails);
            ordersDtos.add(ordersDto);
        }
        BeanUtils.copyProperties(ordersPage,ordersDtoPage,"records");
        ordersDtoPage.setRecords(ordersDtos);
        return Result.success(ordersDtoPage);
    }

    // 用户提交订单
    @PostMapping("/submit")
    Result<String> orderSubmit(@RequestBody Orders orders, HttpServletRequest request){
        log.info("order: {}",orders);
        Long userId = (Long)request.getSession().getAttribute("user");
        BigDecimal amount = BigDecimal.valueOf(0);

        AddressBook addressBook = addressBookService.getById(orders.getAddressBookId());
        User user = userService.getById(userId);
        // 订单初始化
        orders.setNumber(UUID.randomUUID().toString());
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setUserId(userId);
        orders.setStatus(2);
        orders.setConsignee(addressBook.getConsignee());
        orders.setUserName(user.getName());
        orders.setPhone(user.getPhone());
        String address=addressBook.getProvinceName()==null?"":addressBook.getProvinceName();
        address+=addressBook.getCityName()==null?"":addressBook.getCityName();
        address+=addressBook.getDistrictName()==null?"":addressBook.getDistrictName();
        address+=addressBook.getDetail()==null?"":addressBook.getDetail();
        log.info("address : {}",address);
        orders.setAddress(address);

        LambdaQueryWrapper<ShoppingCart> shoppingCartLambdaQueryWrapper = new LambdaQueryWrapper<>();
        shoppingCartLambdaQueryWrapper.eq(ShoppingCart::getUserId,userId);

        List<ShoppingCart> list = shoppingCartService.list(shoppingCartLambdaQueryWrapper);

        // 设置订单金额
        for (int i = 0; i < list.size(); i++) {
            amount = amount.add(list.get(i).getAmount());

            log.info("amount: {}",amount);
        }
        orders.setAmount(amount);


        //添加订单到订单表
        ordersService.save(orders);
        Long orderId = orders.getId();
        // 添加orderDetail
        for (int i = 0; i < list.size(); i++) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(list.get(i),orderDetail);
            orderDetail.setOrderId(orderId);
            orderDetailService.save(orderDetail);
        }

        // 清空当前用户id的购物车
        shoppingCartService.remove(shoppingCartLambdaQueryWrapper);

        return Result.success("提交成功");
    }

    // 修改订单状态
    @PutMapping
    Result<String> orderChangeStatus(@RequestBody Orders orders){
        ordersService.updateById(orders);
        return Result.success("修改成功");
    }

}
